package com.example.javaee_blog.controller;

import com.example.javaee_blog.constants.Constant;
import com.example.javaee_blog.model.Result;
import com.example.javaee_blog.model.UserInfo;
import com.example.javaee_blog.service.UserService;
import com.example.javaee_blog.utils.JwtUtils;
import com.example.javaee_blog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName, String password){
        if(!StringUtils.hasLength(userName)
                || !StringUtils.hasLength(password)){
            return Result.fail("用户或密码不能为空");
        }
        UserInfo userInfo = userService.queryByName(userName);
        if(userInfo==null || userInfo.getId()<=0){
            return Result.fail("用户不存在");
        }
//        if(!password.equals(userInfo.getPassword())){
//            return Result.fail("用户或密码错误");
//        }
        if(!SecurityUtils.verify(password, userInfo.getPassword())){
            return Result.fail("用户或密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put(Constant.USER_ID, userInfo.getId());
        map.put(Constant.USER_NAME, userInfo.getUserName());
        String token = JwtUtils.getToken(map);

        return Result.success(token);
    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String token = request.getHeader(Constant.USER_TOKEN_HANDLER);
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if(userId==null || userId<=0)
            return null;
        UserInfo userInfo = userService.queryById(userId);
        userInfo.setPassword("");
        return userInfo;
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        if(blogId==null || blogId<1){
            return null;
        }
        UserInfo userInfo = userService.getAuthorByBlogId(blogId);
        userInfo.setPassword("");
        return userInfo;
    }
}
